package cn.zhoushengdao.eyeprotector

import android.app.usage.UsageStatsManager
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import cn.zhoushengdao.eyeprotector.ui.theme.EyeProtectorTheme

class MainActivity : ComponentActivity() {
    companion object {
        private const val REFRESH_INTERVAL = 10000L // 10 秒刷新一次
    }

    private val handler = Handler(Looper.getMainLooper())
    private val refreshRunnable = object : Runnable {
        override fun run() {
            updateStats()
            handler.postDelayed(this, REFRESH_INTERVAL)
        }
    }

    // UI 状态
    private var serviceStatus by mutableStateOf("未知")
    private var totalUsage by mutableLongStateOf(0L)
    private var timeSinceLast by mutableLongStateOf(0L)
    private var showPermissionDialog by mutableStateOf(false) // 控制权限对话框显示

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            EyeProtectorTheme {
                // 权限对话框状态管理
                if (showPermissionDialog) {
                    PermissionInstructionsDialog(
                        onDismiss = { showPermissionDialog = false })
                }

                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {
                    MainScreen(
                        serviceStatus = serviceStatus,
                        spaceBetweenTipsMinutes = EyeProtectorService.SPACE_BETWEEN_TIPS_MINUTES,
                        pastUsageStatsCheckMinutes = EyeProtectorService.PAST_USAGE_STATS_CHECK_MINUTES,
                        maxAllowedUsageMinutes = EyeProtectorService.MAX_ALLOWED_USAGE_MINUTES,
                        totalUsage = totalUsage,
                        timeSinceLast = timeSinceLast,
                        onRefresh = { updateStats() },
                        onGrantPermissions = { grantPermissions() },
                        onDisableBatteryOptimization = { disableBatteryOptimization() },
                        onManufacturerSettings = { openManufacturerSpecificSettings() },
                        onShowOverlay = { triggerImmediateOverlay() })
                }
            }
        }

        // 检查权限并启动服务
        if (checkPermissions()) {
            startService()
        }

        // 启动统计数据刷新
        updateStats()
    }

    override fun onResume() {
        super.onResume()
        // 启动定时刷新
        handler.postDelayed(refreshRunnable, REFRESH_INTERVAL)
    }

    override fun onPause() {
        super.onPause()
        // 停止定时刷新
        handler.removeCallbacks(refreshRunnable)
    }

    private fun updateStats() {
        try {
            // 获取服务状态
            val isRunning = EyeProtectorService.isServiceRunning
            serviceStatus =
                if (isRunning) getString(R.string.running) else getString(R.string.not_running)

            // 获取服务统计数据
            totalUsage = EyeProtectorService.lastTotalUsageInPeriod
            timeSinceLast = EyeProtectorService.previousTipSpace

        } catch (_: Exception) {
            serviceStatus = getString(R.string.failed)
        }
    }

    private fun checkPermissions(): Boolean {
        return Settings.canDrawOverlays(this) && hasUsageStatsPermission()
    }

    private fun grantPermissions() {
        // 请求悬浮窗权限
        if (!Settings.canDrawOverlays(this)) {
            try {
                Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
                    startActivity(this)
                }
            } catch (_: Exception) {
                openAppSettings()
            }
            return
        }

        // 请求使用统计权限
        if (!hasUsageStatsPermission()) {
            try {
                Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS).apply {
                    startActivity(this)
                }
            } catch (_: Exception) {
                openAppSettings()
            }
            return
        }

        showToast(getString(R.string.all_permissions_granted_message))
    }

    private fun showToast(message: String) {
        runOnUiThread {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }
    }

    private fun openAppSettings() {
        try {
            Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = "package:$packageName".toUri()
                startActivity(this)
            }
        } catch (_: Exception) {
            showPermissionDialog = true
        }
    }

    private fun hasUsageStatsPermission(): Boolean {
        val pm = getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
        val currentTime = System.currentTimeMillis()
        val stats = pm.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY, currentTime - 1000 * 60, currentTime
        )
        return !stats.isNullOrEmpty()
    }

    private fun disableBatteryOptimization() {
        try {
            Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
                startActivity(this)
            }
        } catch (_: Exception) {
            openStandardBatterySettings()
        }
    }

    private fun startService() {
        // 启动服务
        startForegroundService(Intent(this, EyeProtectorService::class.java))
    }

    private fun triggerImmediateOverlay() {
        val serviceIntent = Intent(this, EyeProtectorService::class.java).apply {
            action = "SHOW_OVERLAY_IMMEDIATELY"
        }
        startForegroundService(serviceIntent)
    }

    // 厂商特定设置
    @Suppress("SpellCheckingInspection")
    private fun openManufacturerSpecificSettings() {
        try {
            val manufacturer = Build.MANUFACTURER.orEmpty().lowercase()

            when {
                manufacturer.contains("huawei") || manufacturer.contains("honor") -> {
                    tryHonorSettings()
                }

                manufacturer.contains("xiaomi") || manufacturer.contains("redmi") -> {
                    // 小米
                    try {
                        Intent("miui.intent.action.APP_PERM_EDITOR").apply {
                            setClassName(
                                "com.miui.securitycenter",
                                "com.miui.permcenter.permissions.PermissionsEditorActivity"
                            )
                            putExtra("extra_pkgname", packageName)
                            if (packageManager.resolveActivity(this, 0) != null) {
                                startActivity(this)
                            } else {
                                throw Exception("Activity not found")
                            }
                        }
                    } catch (_: Exception) {
                        openStandardBatterySettings()
                    }
                }

                manufacturer.contains("oppo") -> {
                    // OPPO
                    try {
                        Intent().apply {
                            setClassName(
                                "com.coloros.safecenter",
                                "com.coloros.safecenter.permission.startup.StartupAppListActivity"
                            )
                            if (packageManager.resolveActivity(this, 0) != null) {
                                startActivity(this)
                            } else {
                                throw Exception("Activity not found")
                            }
                        }
                    } catch (_: Exception) {
                        openStandardBatterySettings()
                    }
                }

                manufacturer.contains("vivo") -> {
                    // Vivo
                    try {
                        Intent().apply {
                            setClassName(
                                "com.vivo.abe",
                                "com.vivo.applicationbehaviorengine.ui.ExcessivePowerManagerActivity"
                            )
                            if (packageManager.resolveActivity(this, 0) != null) {
                                startActivity(this)
                            } else {
                                throw Exception("Activity not found")
                            }
                        }
                    } catch (_: Exception) {
                        openStandardBatterySettings()
                    }
                }

                else -> {
                    openStandardBatterySettings()
                }
            }
        } catch (_: Exception) {
            openStandardBatterySettings()
        }
    }

    @Suppress("SpellCheckingInspection")
    private fun tryHonorSettings() {
        try {
            // 尝试荣耀专用设置
            Intent().apply {
                setClassName(
                    "com.hihonor.systemmanager",
                    "com.hihonor.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
                )
                if (packageManager.resolveActivity(this, 0) != null) {
                    startActivity(this)
                } else {
                    throw Exception("Activity not found")
                }
            }
        } catch (_: Exception) {
            try {
                // 尝试华为通用设置
                Intent().apply {
                    setClassName(
                        "com.huawei.systemmanager",
                        "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
                    )
                    if (packageManager.resolveActivity(this, 0) != null) {
                        startActivity(this)
                    } else {
                        throw Exception("Activity not found")
                    }
                }
            } catch (_: Exception) {
                openStandardBatterySettings()
            }
        }
    }

    private fun openStandardBatterySettings() {
        try {
            Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
                startActivity(this)
            }
        } catch (_: Exception) {
            // 最终回退方案
            Intent(Settings.ACTION_SETTINGS).apply {
                try {
                    startActivity(this)
                } catch (_: Exception) {
                    // 处理所有异常
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    serviceStatus: String,
    spaceBetweenTipsMinutes: Int,
    pastUsageStatsCheckMinutes: Int,
    maxAllowedUsageMinutes: Int,
    totalUsage: Long,
    timeSinceLast: Long,
    onRefresh: () -> Unit,
    onGrantPermissions: () -> Unit,
    onDisableBatteryOptimization: () -> Unit,
    onManufacturerSettings: () -> Unit,
    onShowOverlay: () -> Unit
) {
    val scrollState = rememberScrollState()

    Scaffold(topBar = {
        TopAppBar(
            title = {
                Text(
                    text = stringResource(R.string.app_name),
                    style = MaterialTheme.typography.headlineSmall
                )
            })
    }) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
                .fillMaxSize()
                .verticalScroll(scrollState)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 统计数据卡片
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = stringResource(R.string.service_status, serviceStatus),
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Bold
                    )

                    Text(
                        text = stringResource(
                            R.string.last_some_min_usage, pastUsageStatsCheckMinutes, totalUsage
                        ), style = MaterialTheme.typography.bodyMedium
                    )

                    Text(
                        text = stringResource(R.string.time_since_last_reminder, timeSinceLast),
                        style = MaterialTheme.typography.bodyMedium
                    )

                    Text(
                        text = stringResource(
                            R.string.time_limit,
                            spaceBetweenTipsMinutes,
                            pastUsageStatsCheckMinutes,
                            maxAllowedUsageMinutes
                        ), style = MaterialTheme.typography.bodyMedium
                    )
                }
            }

            // 功能按钮
            Button(
                onClick = onRefresh, modifier = Modifier.fillMaxWidth(0.8f)
            ) {
                Text(stringResource(R.string.refresh_data))
            }

            Button(
                onClick = onGrantPermissions, modifier = Modifier.fillMaxWidth(0.8f)
            ) {
                Text(stringResource(R.string.grant_permissions))
            }

            Button(
                onClick = onDisableBatteryOptimization, modifier = Modifier.fillMaxWidth(0.8f)
            ) {
                Text(stringResource(R.string.disable_battery_optimization))
            }

            Button(
                onClick = onManufacturerSettings, modifier = Modifier.fillMaxWidth(0.8f)
            ) {
                Text(stringResource(R.string.app_background_settings))
            }

            // 立即显示提醒按钮
            Button(
                onClick = onShowOverlay,
                modifier = Modifier.fillMaxWidth(0.8f),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.tertiaryContainer,
                    contentColor = MaterialTheme.colorScheme.onTertiaryContainer
                )
            ) {
                Text(stringResource(R.string.show_overlay_now))
            }
        }
    }
}

@Composable
fun PermissionInstructionsDialog(
    onDismiss: () -> Unit
) {
    AlertDialog(onDismissRequest = onDismiss, title = {
        Text(
            text = stringResource(R.string.permission_required_title),
            style = MaterialTheme.typography.headlineSmall
        )
    }, text = {
        Text(
            text = stringResource(R.string.manual_permission_instructions),
            style = MaterialTheme.typography.bodyMedium
        )
    }, confirmButton = {
        TextButton(
            onClick = onDismiss
        ) {
            Text(stringResource(android.R.string.ok))
        }
    })
}
